﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using BookExchange.Business;
using BookExchange.Configuration;
using BookExchange.ODataService;
using BookExchange.Utility;
using BookExchange.ViewModel;

namespace BookExchange
{
    public partial class SiteMaster : MasterPage
    {
        public List<Request> getLastestListRequest{ get{ return requestList;}} 

        private RequestBusiness requestBusiness;
        private List<Request> requestList; 

        private const string AntiXsrfTokenKey = "__AntiXsrfToken";
        private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
        private string _antiXsrfTokenValue;

        private static bool autoLoginIfDebug = true;
        private CategoryBusiness categoryBus;
        private MemberBusiness memberBus;

        private List<Category> categoryList;

        public SiteMaster()
            : base()
        {
            categoryBus = new CategoryBusiness();
            memberBus = new MemberBusiness();
            requestBusiness = new RequestBusiness ();
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            
            // The code below helps to protect against XSRF attacks
            var requestCookie = Request.Cookies[AntiXsrfTokenKey];
            Guid requestCookieGuidValue;
            if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
            {
                // Use the Anti-XSRF token from the cookie
                _antiXsrfTokenValue = requestCookie.Value;
                Page.ViewStateUserKey = _antiXsrfTokenValue;
            }
            else
            {
                // Generate a new Anti-XSRF token and save to the cookie
                _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
                Page.ViewStateUserKey = _antiXsrfTokenValue;

                var responseCookie = new HttpCookie(AntiXsrfTokenKey)
                {
                    HttpOnly = true,
                    Value = _antiXsrfTokenValue
                };
                if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
                {
                    responseCookie.Secure = true;
                }
                Response.Cookies.Set(responseCookie);
            }

            Page.PreLoad += master_Page_PreLoad;
        }

        protected void master_Page_PreLoad(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Set Anti-XSRF token
                ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
                ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
            }
            else
            {
                // Validate the Anti-XSRF token
                if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                    || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
                {
                    throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                AutoLoginIfDebug();

                LoadCategories();

                BindCategories();

                
            }
            LoadSlideShow();
            DisplayLoginStatus();

            //Hiển thị từ mà user đã gõ vào ô search
            //DisplaySearchText();
        }

        private void LoadSlideShow()
        {
            requestList = requestBusiness.GetTopRequest(RequestType.Post,AppConfiguration.Instance.AmountOfSlideShow*AppConfiguration.Instance.ItemPerSlideShow);
        }


        private void DisplaySearchText()
        {
            txtSearchText.Value = txtSearchText.Value;
        }

        private void LoadCategories()
        {
            categoryList = categoryBus.GetCategoryList();
        }

        private void BindCategories()
        {
            rptPostCategory.DataSource = categoryList;
            rptPostCategory.DataBind();

            //rptRequestCategory.DataSource = categoryList;
            //rptRequestCategory.DataBind();
        }

        private void AutoLoginIfDebug()
        {
#if DEBUG
            if (autoLoginIfDebug == false)
            {
                return;
            }

            Member m = new Member()
            {
                MemberCode = 1,
                Email = "admin@yahoo.com",
                DisplayName = "ledangvu",
                RoleCode = 1
            };
            MemberViewModel mem = new MemberViewModel(m);
            Session[AppConstant.CurrentUser] = mem;
            autoLoginIfDebug = false;
#endif
        }

        private void DisplayLoginStatus()
        {
            //Kiểm tra trạng thái đăng nhập
            if (IsUserValidated)// Đăng nhập rồi 
            {
                nta_box_dangnhap.Visible = false;
                nta_box_thongtin_user.Visible = true;
                lblUsername.InnerText = string.Format("{0}", (Session[AppConstant.CurrentUser] as MemberViewModel).DisplayName);
            }
            else
            {
                nta_box_dangnhap.Visible = true;
                nta_box_thongtin_user.Visible = false;
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {


            //Đọc ra email & password từ màn hình chính
            string email = txtEmail.Text;
            string pw = txtPassword.Text;
            bool rememberMe = chkRememberme.Checked;

            BookExchange.Login loginPage = new Login();
            loginPage.LoginWithUser(email, pw, rememberMe);

            //validate xem có hợp lệ hay không
            var existsMember = memberBus.GetMember(email, pw);

            ////Nếu tồn tại thì set userID vào sesion rồi 
            //if (existsMember != null)
            //{
            //    MemberViewModel memViewModel = new MemberViewModel(existsMember);
            //    Session[AppConstant.CurrentUser] = memViewModel;
            //    Session.Timeout = rememberMe ?
            //        AppConfiguration.Instance.MaximumSessionTimeout : AppConfiguration.Instance.DefaultSessionTimeout;               
            //}
            //else
            //{
            //    //set text to errorLabel
            //}

            DisplayLoginStatus();

            //Trả người dùng về trang web cũ            
            Response.Redirect(Page.Request.UrlReferrer.ToString());

        }

        private bool IsUserValidated
        {
            get
            {
                return Session[AppConstant.CurrentUser] != null;
            }
        }
    }
}